<?php

namespace Addons\UserCenter\Controller;

use Home\Controller\AddonsController;
use User\Api\UserApi;

class UserCenterController extends AddonsController {

    //记录用户上一次打开用户中心的时间戳，用来获取在此期间用户会收到那些提示
    public $lastOpen0;
    public $lastOpen1;
    public $lastOpen2;
    public $lastOpen3;
    public $lastOpen4;
    /**
     *
     */
    function _initialize() {
        //粉丝登录
        if(session('is_follow_login') == 1){
            $this->lastOpen0 = cookie('lastOpen0');
            $this->lastOpen1 = cookie('lastOpen1');
            $this->lastOpen2 = cookie('lastOpen2');
            $this->lastOpen3 = cookie('lastOpen3');
            $this->lastOpen4 = cookie('lastOpen4');
            //判断用户是否通过微信的网页授权过
            if(empty(session('oauth2')) || !empty(session('oauth2.errcode')))
            {
                if(isset($_GET['code'])){
                    getUserInfo();
                }else{
                    wx_login(GetCurUrl());
                }
            }
            C ( 'EDITOR_UPLOAD.rootPath', './Uploads/Editor/' . get_token () . '/' );
        }else{
            parent::_initialize();
        }

    }

	/**
	 * 显示微信用户列表数据
	 */
	public function lists() {

        $this->assign ( 'add_button', false );
		$this->assign ( 'del_button', false );
		$this->assign ( 'check_all', false );
		
		$model = $this->getModel ( 'follow' );
		parent::common_lists ( $model, 0, '', 'nickname desc');
	}
	// 用户绑定
    public function edit() {
		$is_admin_edit = false;
		if(!empty($_REQUEST['id']) && is_login()){
			$map['id'] = intval($_REQUEST['id']);
			$is_admin_edit = true;
			$msg = '编辑';
			$html = 'edit';
		}else{
			$msg = '绑定';
		    $openid = $map ['openid'] = session ('oauth2.openid');
			$html = 'moblieForm';
		}
		$token = $map ['token'] = get_token ();
		$model = $this->getModel ( 'follow' );
		
		if (IS_POST) {
			!$is_admin_edit && $_POST['status'] = 2;
            if(!$is_admin_edit){
                // 自动从微信接口获取用户信息
                empty($openid) || $info = getWeixinUserInfo ( $openid, $token );
                if (is_array ( $info )) {
                    if (empty ( $data ['headimgurl'] ) && ! empty ( $info ['headimgurl'] )) {
                        // 把微信头像转到WeiPHP的通用图片ID保存 TODO
                        $_POST ['headimgurl'] = $info ['headimgurl'];
                    }
                }
            }
			$Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
			// 获取模型的字段信息
			$Model = $this->checkAttr ( $Model, $model ['id'] );
            unset($_POST['id']);
			if ($Model->create () && $Model->where ( $map )->save ()) {
				//lastsql();exit;
//				$url = '';
//				$bind_backurl = cookie('__forward__');
//				$config = getAddonConfig ( 'UserCenter' );
//				$jumpurl = $config['jumpurl'];
				
//				if(!empty($bind_backurl)){
//					$url = $bind_backurl;
//					cookie('__forward__', NULL);
//				}elseif(!empty($jumpurl)){
//					$url = $jumpurl;
//				}elseif(!$is_admin_edit){
                if(session('is_follow_login') == 1){
                    $url = addons_url ( 'UserCenter://UserCenter/userCenter', $map );
                }else{
                    $url = addons_url ( 'UserCenter://UserCenter/lists' );
                }

//				}
                if($redirect_url = get_redirect_url()){
                    $url = $redirect_url;
                    set_redirect_url(null);
                }
				$this->success ( $msg.'成功！',  $url);
			} else {
//				lastsql();
//				dump($map);exit;
				$this->error ( $Model->getError () );
			}
		} else {
			$fields = get_model_attribute ( $model ['id'] );
			if(!$is_admin_edit){
				$fieldArr = array('nickname','sex','mobile', 'company','qq','email'); //headimgurl
				foreach($fields[1] as $k=>$vo){
					if(!in_array($vo['name'], $fieldArr))
					   unset($fields[1][$k]);
				}
			}

			// 获取数据
			$data = M ( get_table_name ( $model ['id'] ) )->where ( $map )->find ();
			
            $token = get_token ();
            if (isset ( $data ['token'] ) && $token != $data ['token'] && defined ( 'ADDON_PUBLIC_PATH' )) {
                $this->error ( '非法访问！' );
            }
            //是否指定跳转地址
            I('redirect_url', false) && set_redirect_url(I('redirect_url', '', 'urldecode'));

			$this->assign ( 'fields', $fields );
			$this->assign ( 'data', $data );
			$this->meta_title = $msg.'用户消息';
			
			$this->assign('post_url', U('edit'));

			$this->display ($html);
		}
	
		
	}
	public function userCenter() {
        //当前粉丝信息
        $map ['token'] = get_token();
        $map ['openid'] = session ('oauth2.openid');
        $user = M ( 'follow' )->where ( $map )->find ();
        if($user['status'] < 2){//未绑定跳转到绑定页
            redirect(addons_url('UserCenter://UserCenter/edit', $map));
        }
        //获取当前用户的项目
        $project_lists = M('project')->where($map)->select();
        $project['total'] = count($project_lists);//全部项目数
        foreach($project_lists as $v){
            switch($v['status']){
                case '0':
                    if($v['update_time'] >= $this->lastOpen0){
                        $project['notice_npass']++;
                    }
                    $project['npass']++;
                    break;
                case '1':
                    if($v['update_time'] >= $this->lastOpen1){
                        $project['notice_ing']++;
                    }
                    $project['ing']++;
                    break;
                case '2':
                    if($v['update_time'] >= $this->lastOpen2){
                        $project['notice_pass']++;
                    }
                    $project['pass']++;
                    break;
                case '3':
                    if($v['update_time'] >= $this->lastOpen3){
                        $project['notice_sign']++;
                    }
                    $project['sign']++;
                    break;
                case '4':
                    if($v['update_time'] >= $this->lastOpen4){
                        $project['notice_nsign']++;
                    }
                    $project['nsign']++;
                    break;
            }
        }
        //获取用户积分
        $map['redirect_url'] = urlencode(SITE_URL . __SELF__);
        //获取背景图
        $config = get_addon_config('UserCenter');
        $this->assign('config', $config);
        $this->assign('project', $project);
        $this->assign('map', $map);
        $this->assign($user);
		$this->display();
	}
	function config(){
		// 使用提示
		$normal_tips = '如需用户关注时提示先绑定，请进入‘欢迎语’插件按提示进行配置提示语';
		$this->assign ( 'normal_tips', $normal_tips );
		
		parent::config();
	}
}
